import request from '../../../util/request'
import PubSub from 'pubsub-js'
import moment from 'moment'
//获取全局实例
const appInstance = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPlay: false, //音乐是否播放
    song: {}, //歌曲详情
    musicId: '', //音乐Id
    musicLink: '',
    currentTime: '00:00', //进度条开始时间
    durationTime: '00:00', //进度条结束时间
    currentWidth: 0, //实时进度条的宽度
  },

  /**
   * 生命周期函数--监听页面加载
   * options:用于接收路由跳转传过来的参数
   */
  onLoad(options) {
    let musicId = options.musicId
    this.setData({
      musicId
    })
    this.getMusicInfo(musicId)
    this.musicControl(true, musicId)
    //判断当前页面的音乐是否在播放
    if (appInstance.globalData.isMusicPlay && appInstance.globalData.musicId === musicId) {
      this.setData({
        isPlay: true
      })
    }
    //创建控制音乐播放的实例
    this.backgroundAudioManager = wx.getBackgroundAudioManager();
    //控制系统播放回调
    this.backgroundAudioManager.onPlay(() => {
      this.changePlayState(true)
      //修改全局音乐播放的状态
      appInstance.globalData.musicId = musicId;
    });
    //控制系统暂停的回调
    this.backgroundAudioManager.onPause(() => {
      this.changePlayState(false)
    });
    //监听用户关闭播放 
    this.backgroundAudioManager.onStop(() => {
      this.changePlayState(false)
    });
    //监听音乐自然播放结束 
    this.backgroundAudioManager.onEnded(() => {
      // 自动切换至下一首，并自动播放
      PubSub.publish('switchType', 'next')
      //将实时进度条长度还原成0
      this.setData({
        currentWidth: 0,
        currentTime: '00:00',
      })
    });
    // 监听音乐播放实时进度
    this.backgroundAudioManager.onTimeUpdate(() => {
      let currentTime = moment(this.backgroundAudioManager.currentTime * 1000).format('mm:ss')
      let currentWidth = this.backgroundAudioManager.currentTime / this.backgroundAudioManager.duration * 450
      this.setData({
        currentTime,
        currentWidth
      })
    })
  },
  //修改播放状态
  changePlayState(isPlay) {
    this.setData({
      isPlay
    })
    appInstance.globalData.isMusicPlay = isPlay;
  },
  //获取音乐详情
  async getMusicInfo(musicId) {
    let songData = await request('/song/detail', {
      ids: musicId
    })
    let durationTime = moment(songData.songs[0].dt).format('mm:ss')
    this.setData({
      song: songData.songs[0],
      durationTime
    })
    //动态修改窗口标题
    wx.setNavigationBarTitle({
      title: this.data.song.name,
    })
  },
  // 点击播放或者暂停的回调
  handleMusicPlay() {
    let isPlay = !this.data.isPlay
    // this.setData({
    //   isPlay
    // })
    let {
      musicId,
      musicLink
    } = this.data
    this.musicControl(isPlay, musicId, musicLink)
  },
  //音乐暂停或者播放实现功能
  async musicControl(isPlay, musicId, musicLink) {
    if (isPlay) {
      if (!musicLink) {
        //获取音乐播放的连接
        let musicLinkData = await request('/song/url', {
          id: musicId
        })
        musicLink = musicLinkData.data[0].url
        this.setData({
          musicLink
        })
      }

      this.backgroundAudioManager.src = musicLink
      this.backgroundAudioManager.title = this.data.song.name
    } else {
      // 暂停音乐
      this.backgroundAudioManager.pause();
    }
  },
  handleSwitchMusic(event) {
    let type = event.currentTarget.id;
    this.backgroundAudioManager.stop();
    PubSub.subscribe('musicId', (_, musicId) => {
      this.getMusicInfo(musicId)
      this.musicControl(true, musicId)
      //取消订阅
      PubSub.unsubscribe('musicId')
    })
    PubSub.subscribe('musicIdIndex', (_, musicId) => {
      this.getMusicInfo(musicId)
      this.musicControl(true, musicId)
      //取消订阅
      PubSub.unsubscribe('musicIdIndex')
    })
    PubSub.subscribe('musicSearch', (_, musicId) => {
      this.getMusicInfo(musicId)
      this.musicControl(true, musicId)
      //取消订阅
      PubSub.unsubscribe('musicSearch')
    })
    PubSub.subscribe('musicRecommend', (_, musicId) => {
      this.getMusicInfo(musicId)
      this.musicControl(true, musicId)
      //取消订阅
      PubSub.unsubscribe('musicRecommend')
    })
    PubSub.publish('switchType', type)
    PubSub.publish('switchTypeIndex', type)
    PubSub.publish('switchTypeSearch', type)
    PubSub.publish('switchTypeRecommend', type)


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})